package phoenix.web.test_objects;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.testng.TestException;
import phoenix.core.PhoenixManager;
import phoenix.core.base.extensions.TestBaseWebExt;
import phoenix.core.data_models.TestUserDataModel;
import phoenix.web.test_objects.data_model.NotificationsAlerts;
import phoenix.web.test_objects.data_providers.MessengerDataProvider;

/**
 * Created by AlexGolovko on 07.08.2014.
 */
public class MessengerTests extends TestBaseWebExt
{
	public MessengerTests(PhoenixManager phoenix)
	{
		super(phoenix);
	}

	private static Integer n_messages = 0;
	// Data
	public MessengerDataProvider dataProviders = new MessengerDataProvider(manager);

	/**
	 * Tests communication from Search results to different users
	 * @param p_userRecipient
	 */
	public void messageFromSearch(TestUserDataModel[] p_userRecipient)
	{
		try
		{
			wd().openURL(testUser().getAutologin());
			this.beforeInteractionsFromSearch(p_userRecipient);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("beforeInteractionsFromSearch " + p_ex.toString());
		}

		try
		{
			wd().openURL(testUser().getAutologin());
			wd().openPage("/favorites");
			// Make test actions
			this.interactionsFromSearch(p_userRecipient[0]);
			this.interactionsFromSearch(p_userRecipient[1]);

			// Verify test result
			if (wd().isUrlContains("pay", false))
			{
				throw new TestException("Payment page is detected, looks like some problem with messenger");
			}
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("interactionsFromSearch " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
		}
	}

	private void beforeInteractionsFromSearch(TestUserDataModel[] p_user)
	{
		try
		{
			// Add users to favorits
			wd().openURL(testUser().getAutologin());
			// userPageTests.addUsersToFriends(p_user);
			// Unset Hot status
			manager.backend().searchPage().unmarkUsersAsHot(p_user);
		}
		catch (Exception p_ex)
		{
			log().warn("beforeInteractionsFromSearch " + p_ex.toString());
		}
	}

	private void interactionsFromSearch(TestUserDataModel p_userRecipient)
	{
		try
		{
			// page().searchPage().openMessangerByIdFromSearch(p_userRecipient);
			// this.sendChat("Hello, how a U?", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("interactionsFromSearch " + p_ex.toString());
		}
	}

	public void messengerModesTest()
	{
		try
		{
			// Large
			page().menuPage().clickTopMenuMessagedMe();
			if (!page().messenger().isLargePresent())
			{
				throw new TestException("Can't find large window");
			}

			// Small
			page().messenger().clickPopIn();
			if (!page().messenger().isSmallPresent())
			{
				throw new TestException("Can't find small window");
			}

			// Minimized
			page().messenger().clickMinimize();

			if (!page().messenger().isMinimizedPresent())
			{
				throw new TestException("Minimized window isn't found");
			}
			// Small with list
			page().messenger().clickMaximize();
			// page().messenger().checkForSmallWithListWindow(); // siteBug
			// https://redmine.platformphoenix.com/issues/126519
			// Large
			page().messenger().clickPopOut();
			if (!page().messenger().isLargePresent())
			{
				throw new TestException("Can't find large window");
			}

		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("messengerModesTest " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
		}
	}

	public void massageFromTopMenuProfile(TestUserDataModel p_user)
	{
		try
		{
			// Send message
			wd().openURL(p_user.getAutologin());
			wd().openUserProfile(testUser());
			page().messenger().clickMessenger();
			// this.sendChat("Hello, how a U?", true);

			// Check
			wd().wait(30); // Wait for proper sync
			wd().openURL(testUser().getAutologin());
			page().menuPage().clickTopMenuMessagedMe();

		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("massageFromTopMenuProfile " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
		}
	}

	public void messageDeliveryStatusTest(TestUserDataModel p_user)
	{
		try
		{
			wd().openURL(p_user.getAutologin());
			wd().openUserProfile(testUser());
			page().messenger().clickMessenger();
			// this.sendChat("Hello, how a U?", true);

			// Check unread status
			page().messenger().clickMessenger();
			page().messenger().checkStatusOfDelivery(false);

			// Read message
			wd().openURL(testUser().getAutologin());
			wd().openUserProfile(p_user);
			page().messenger().clickMessenger();

			// Check read status
			wd().openURL(p_user.getAutologin());
			wd().openUserProfile(testUser());
			page().messenger().clickMessenger();
			page().messenger().checkStatusOfDelivery(true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("messageSizeChangeTest " + p_ex.toString());
		}
		finally
		{
			wd().openURL(testUser().getAutologin());
			test().forErrors();
		}
	}

	public void messengerOpenTest(TestUserDataModel[] p_userRecipient)
	{
		try
		{
			this.beforeInteractionsFromSearch(p_userRecipient);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("beforeInteractionsFromSearch " + p_ex.toString());
		}

		try
		{
			wd().openPage("/favorites");
			wd().waitForVisibility(page().searchPage().elements().imgSiteLogo, "Site loading");
			// Check for small mode ( profile, search )
			page().searchPage().openMessangerByIdFromSearch(p_userRecipient[0]);
			if (!page().messenger().isSmallPresent())
			{
				throw new TestException("Can't find small window");
			}
			page().messenger().clickClose();

			// Check for small mode with list
			page().searchPage().openMessangerByIdFromSearch(p_userRecipient[0]);
			page().searchPage().openMessangerByIdFromSearch(p_userRecipient[1]);
			// page().messenger().checkForSmallWithListWindow(); // siteBug
			// https://redmine.platformphoenix.com/issues/126519
			page().messenger().clickClose();

			// Check for large mode
			wd().openPage("/search");
			wd().waitForVisibility(page().searchPage().elements().imgSiteLogo, "Site loading");
			page().menuPage().clickTopMenuMessagedMe();
			if (!page().messenger().isLargePresent())
			{
				throw new TestException("Can't find large window");
			}
			page().messenger().clickClose();

		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("messengerOpenTest " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
		}
	}

	/**
	 * Paid user clicks at the first element of the list, we do expect that user goes at the end of the list and
	 * decrement of counter.
	 * Free user clicks on profiles by turn , we do expect that user is unable to read messages
	 * @param p_user Array of senders
	 */
	public void messageNotificationTest(TestUserDataModel[] p_user, ArrayList<Integer> userOrderFixture)
	{
		try
		{
			// Make actions, three users will send message
			Map<Integer, String[]> p_list = this.prepareMessages(p_user);
			// Check for correct number of messages
			if (p_list.size() != p_user.length)
			{
				throw new TestException("We do expect " + p_user.length + " users in list, but found " + p_list.size());
			}

			// Check alerts presents
			wd().openAutologin(testUser());
			page().searchPage().waitForPageLoad();
			page().menuPage().clickTopMenuMessagedMe();

			// Case for drop down like flirt
			if (manager.isFlirt() || manager.isMD())
			{
				if (page().menuPage().isSeeAllDisplayed())
				{
					page().menuPage().clickSeeAll();
				}
			}
			else if (manager.isNF())
			{
				wd().wait(2);
				if (page().menuPage().isSeeAllPresent())
				{
					page().menuPage().clickSeeAll();
				}
			}

			if (!page().messenger().isLargePresent())
			{
				throw new TestException("Unable to open messenger");
			}

			// Number of unseen messages
			n_messages = (testUser().isPaid()) ? p_user.length - 1 : p_user.length;

			Map l_listOfUsers = page().messenger().getListOfUsers();

			// Check number of users in list
			if (l_listOfUsers.size() != p_user.length)
			{
				throw new TestException("We do expect " + p_user.length + " users, but found " + l_listOfUsers.size());
			}

			// Click at user, the last sent message ( Barby_third )
			page().messenger().clickById(p_list.get(3)[0]);
			// Prepare for check
			this.usersActions();
			// Test
			this.alertsTest(userOrderFixture.get(0), p_list);

			// Click at user, with screen name ( Barby_second )
			page().messenger().clickById(p_list.get(2)[0]);
			this.usersActions();
			// SiteBug https://redmine.platformphoenix.com/issues/127219
			if (testUser().isPaid())
			{
				n_messages--;
			}
			// this.alertsTest(userOrderFixture.get(1), p_list);

			// Click at user ( Barby_first )
			page().messenger().clickById(p_list.get(1)[0]);
			this.usersActions();
			this.alertsTest(userOrderFixture.get(2), p_list);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("messageNotificationTest " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
		}
	}

	private void usersActions()
	{
		if (testUser().isPaid() != true)
		{
			if (wd().isUrlContains("pay", false))
			{
				page().paymentPage().clickBackToSite();
			}
			wd().openPage("/search");
			page().searchPage().waitForPageLoad();
			if (!page().messenger().isLargePresent())
			{
				page().menuPage().clickTopMenuMessagedMe();
				if (!page().messenger().isLargePresent())
				{
					throw new TestException("Can't find large window");
				}
				// Case for drop down like flirt
				if (manager.isFlirt() || manager.isMD() || manager.isNF())
				{
					if (page().menuPage().isSeeAllPresent())
					{
						page().menuPage().clickSeeAll();
					}
				}
			}
		}
		else
		{
			// Paid user must wait some time for js execution
			wd().wait(2);
		}
	}

	/**
	 * @testBug : https://redmine.platformphoenix.com/issues/127219
	 */
	private void alertsTest(Integer fixtureOrderPosition, Map<Integer, String[]> listFixtureData)
	{

		log().info("Test begins for large window");
		Map<Integer, String[]> list = page().messenger().getListOfUsers();

		String p_errorDetails = "Expected position in list for recipient " + fixtureOrderPosition;

		// Check actual number of users present in messenger list
		test().assertEqualsWithScreen(list.size(), listFixtureData.size(), "actual number of users present in messenger list " + p_errorDetails);

		// Large size
		test().assertEqualsWithScreen(page().messenger().getCounter(), n_messages, "Counter at title large " + p_errorDetails);
		test().assertEqualsWithScreen(page().messenger().getTitle(), "Messenger", "Title for large mode " + p_errorDetails);

		log().info("Test begins for small window");
		page().messenger().clickPopIn();
		// Small size
		if (!page().messenger().isSmallPresent())
		{
			throw new TestException("Can't find small window");
		}
		// We do expect one unread message from single profile
		test().assertEqualsWithScreen(page().messenger().getCounter(), (testUser().isPaid()) ? 0 : 1,
			"Counter at title for small mode " + p_errorDetails);

		// Compare Login name at title
		test().assertEqualsWithScreen(page().messenger().getTitle(), listFixtureData.get(fixtureOrderPosition)[1],
			"Name at title in small mode " + p_errorDetails);

		// Minimized
		log().info("Test begins for minimized window");
		page().messenger().clickMinimize();
		if (!page().messenger().isMinimizedPresent())
		{
			throw new TestException("Minimized window isn't found");
		}

		// We do expect one unread message from single profile
		test().assertEqualsWithScreen(page().messenger().getCounter(), n_messages,
			"Counter at title at minimized mode " + p_errorDetails);

		// Compare Login name at title
		test().assertEqualsWithScreen(page().messenger().getTitle(), this.getTitleNameMinimized(listFixtureData, fixtureOrderPosition),
			"Name at title at minimized mode " + p_errorDetails);

		// Open large messenger for the next check
		page().messenger().clickMaximize();
		if (!page().messenger().isSmallPresent())
		{
			throw new TestException("Can't find small window");
		}
		page().messenger().clickPopOut();
		if (!page().messenger().isLargePresent())
		{
			throw new TestException("Can't find large window");
		}

		if (n_messages != 0)
		{
			// Paid and Free logic actions
			if (testUser().isPaid())
			{
				// Decrement for seen messages
				n_messages--;
			}
		}
	}

	private String getTitleNameMinimized(Map<Integer, String[]> listFixture, Integer fixtureAtlist)
	{
		String p_expectedTitle = null;
		// No unseen messages
		if (n_messages == 0)
		{
			if (testUser().isPaid())
			{
				p_expectedTitle = listFixture.get(fixtureAtlist)[1];
			}
		}
		else if (n_messages == 1)
		{
			if (testUser().isPaid())
			{
				p_expectedTitle = listFixture.get(fixtureAtlist - 1)[1];
			}
		}
		else
		{
			p_expectedTitle = "Messenger";
		}
		return p_expectedTitle;
	}

	public Map<Integer, String[]> prepareMessages(TestUserDataModel[] p_user)
	{
		try
		{
			for (int i = 0; i > p_user.length; i++)
			{
				manager.wd().openAutologin(p_user[i]);
				manager.wd().openPage("/account");
				manager.web().myAccountPage().disableAllNotifications(p_user[i]);
			}
			// Preparation steps
			wd().openAutologin(testUser());
			manager.wd().openPage("/account");
			manager.web().myAccountPage().disableAllNotifications(testUser());

		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("messageNotificationTest " + p_ex.toString());
		}

		Map<Integer, String[]> p_userList = new HashMap<>();
		try
		{
			String message = "Hi, are you there ?";

			for (Integer i = 0; p_user.length > i; i++)
			{
				// Debug
				log().info(" -------------------------------------- ----------------------------------------------- ");
				log().info(i + 1 + " " + p_user[i].getScreenname() + " " + p_user[i].getId());
				log().info(" -------------------------------------- ----------------------------------------------- ");

				this.sendMessage(p_user[i], testUser(), message);

				if (!page().messenger().isMessagePresent(message))
				{
					throw new TestException("prepareMessageNotification : message is not found in messenger");
				}
				page().messenger().clickClose();

				p_userList.put(i + 1, new String[] { p_user[i].getId().toString(), p_user[i].getScreenname().toString(), "1", "1" });

				wd().wait(15);
			}
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("prepareMessageNotification " + p_ex.toString());
		}
		finally
		{
			test().forErrors();
			return p_userList;
		}
	}

	/**
	 * Free => UserPage Send chat message redirect on payment page
	 */
	public void twoMessagesTest(String p_messageKey, TestUserDataModel p_userSender, TestUserDataModel p_userRecipient)
	{
		try
		{
			try
			{
				NotificationsAlerts params = new NotificationsAlerts();
				params.disableAllPopUps(); // Enable site action alerts
				manager.web().myAccountPage().setMatchNotifications(params);
				manager.backend().notificationsSettingsPage().setNotifications(p_userSender, params);

				manager.backend().searchPage().unsetUserAsHot(p_userRecipient);
				manager.backend().searchPage().unsetUserAsScammer(p_userRecipient);
			}
			catch (Exception p_ex)
			{
				log().warn("twoMessagesTest preparing " + p_ex.toString());
			}

			log().info("UserPage Send chat message redirect on payment page");
			// Send chat message
			this.sendMessage(p_userSender, p_userRecipient, p_messageKey);

			if (!page().messenger().isMessagePresent(p_messageKey))
			{
				throw new TestException("Cannot send message to " + p_userRecipient.getId() + " message is not found in messenger");
			}
			page().messenger().clickClose();

			// Attempts to type new chat message
			page().messenger().clickMessenger();

			// MD require message typing
			if (manager.isMD())
			{
				wd().wait(2);
				if (!page().messenger().isLargePresent())
				{
					page().messenger().clickPopOut();
				}
				page().messenger().clickMessengerInput();
				page().messenger().type("test");
			}

			// Wait for appear block payment details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentDetails, "Block 'Payment Detail'");
			// Is payment page URL present
			wd().isUrlContains("/pay/membership?via=chat_type", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("UserPage Send chat message redirect on payment page: " + p_ex.toString());
		}

		// Verifying result
		test().forErrors();
	}

	/**
	 * Free => UserPage Receive chat message redirect on payment page
	 */
	public void recieveChatAtProfileTest(String p_messageKey, TestUserDataModel p_userSender, TestUserDataModel p_userRecipient)
	{
		TestUserDataModel p_origin = p_userSender;

		try
		{
			// Send chat message
			this.sendMessage(p_userRecipient, p_userSender, p_messageKey);

			if (!page().messenger().isMessagePresent(p_messageKey))
			{
				throw new TestException("Cannot send message to " + p_userRecipient.getId() + " message is not found in messenger");
			}
			page().messenger().clickClose();

			// Delivery
			wd().openAutologin(p_userSender);
			wd().openUserProfile(p_userRecipient);
			page().messenger().clickMessenger();

			if (manager.isMD())
			{
				page().messenger().clickPopOut();
				page().messenger().clickUpgradeBanner();
			}

			// Wait for appear block payment details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentDetails, "Block 'Payment Details'");
			// Is payment page URL present
			wd().isUrlContains("/pay/membership?via=chat_type", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("recieveChatTest " + p_ex.toString());
		}
		finally
		{
			// Restore session of test user
			wd().openAutologin(p_origin);
			wd().wait(1);
			// Verifying result
			test().forErrors();
		}
	}

	public void recieveChatAtSearchTest(String p_messageKey, TestUserDataModel p_userSender, TestUserDataModel p_userRecipient)
	{
		TestUserDataModel p_origin = p_userSender;

		try
		{
			// Send chat message
			this.sendMessage(p_userRecipient, p_userSender, p_messageKey);

			if (!page().messenger().isMessagePresent(p_messageKey))
			{
				throw new TestException("Cannot send message to " + p_userRecipient.getId() + " message is not found in messenger");
			}
			page().messenger().clickClose();

			// Delivery
			wd().openAutologin(p_userSender);
			page().searchPage().waitForPageLoad();
			page().searchPage().closeAllPopUps();
			page().menuPage().clickTopMenuMessagedMe();
			wd().wait(1);

			if (manager.isFlirt() || manager.isMD() || manager.isNF())
			{
				if (page().menuPage().isSeeAllPresent())
				{
					page().menuPage().clickSeeAll();
				}
			}

			if (!page().messenger().isLargePresent())
			{
				page().messenger().clickPopOut();
			}
			// Select use in message list
			page().messenger().clickById(p_userRecipient.getId());
			page().messenger().clickUpgradeBanner();

			// Wait for appear block payment details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentDetails, "Block 'Payment Details'");
			// Is payment page URL present
			wd().isUrlContains("/pay/membership?via=chat_read", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("recieveChatTest " + p_ex.toString());
		}
		finally
		{
			// Restore session of test user
			wd().openAutologin(p_origin);
			wd().wait(1);
			// Verifying result
			test().forErrors();
		}
	}

	/**
	 * Free => UserPage Answering chat message redirect on payment page
	 */
	public void answerChatTest(String p_messageKey, TestUserDataModel p_userSender, TestUserDataModel p_userRecipient)
	{
		TestUserDataModel p_origin = p_userSender;
		try
		{
			try
			{
				wd().openAutologin(p_userSender);
				NotificationsAlerts params = new NotificationsAlerts();
				params.disableAllPopUps(); // Enable site action alerts
				manager.web().myAccountPage().setMatchNotifications(params);
				manager.backend().notificationsSettingsPage().setNotifications(p_userSender, params);
			}
			catch (Exception p_ex)
			{
				log().warn("answerChatTest preparing " + p_ex.toString());
			}

			log().info("UserPage Answering chat message redirect on payment page");

			// Send chat message
			this.sendMessage(p_userRecipient, p_userSender, p_messageKey);
			if (!page().messenger().isMessagePresent(p_messageKey))
			{
				throw new TestException("Cannot send message to " + p_userSender.getId() + " message is not found in messenger");
			}
			page().messenger().clickClose();

			// Test begins
			wd().openAutologin(p_userSender);
			wd().openUserProfile(p_userRecipient);
			// Second attempts
			page().messenger().clickMessenger();

			// MD require message typing
			if (manager.isMD())
			{
				wd().wait(2);
				if (!page().messenger().isLargePresent())
				{
					page().messenger().clickPopOut();
				}
				page().messenger().clickMessengerInput();
				page().messenger().type("test");
			}

			// Wait for appear block payment details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentDetails, "Block 'Payment Details'");
			// Is payment page URL present
			wd().isUrlContains("/pay/membership?via=chat_type", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("answerChatTest: " + p_ex.toString());
		}
		finally
		{
			wd().openAutologin(p_origin);
			wd().wait(1);
			// Verifying result
			test().forErrors();
		}

	}

	/**
	 * Free => UserPage Send chat message Hot user redirect on payment page
	 */
	public void hotUserMessageTest(TestUserDataModel p_userHot)
	{
		try
		{
			try
			{
				manager.backend().searchPage().setStatusHot(p_userHot);
				wd().wait(10); // Some time for sync
			}
			catch (Exception p_ex)
			{
				log().warn("hotUserMessageTest preparing " + p_ex.toString());
			}

			wd().openAutologin(testUser());
			wd().openUserProfile(p_userHot);
			// Attempts to type new chat message
			if (!page().messenger().isLargePresent())
			{
				page().messenger().clickMessenger();
			}
			// MD require message typing
			if (manager.isMD())
			{
				wd().wait(2);
				if (!page().messenger().isLargePresent())
				{
					page().messenger().clickPopOut();
				}
				page().messenger().clickMessengerInput();
				page().messenger().type("test");
			}
			// Wait for appear block payment details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentDetails, "Block 'Payment Details' doesn't appear");
			// Is payment page URL present
			wd().isUrlContains("pay/membership?via=chat_type_hot", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("UserPage Send chat message Hot user redirect on payment page: " + p_ex.toString());
		}
		finally
		{
			manager.backend().searchPage().unsetUserAsHot(p_userHot);
			// Verifying result
			test().forErrors();
		}
	}

	/**
	 * Free => Massager send Free 5 messages a day Upgrade redirect on payment page
	 */
	public void fiveMessagesLimitTest(String p_messageKey, TestUserDataModel p_userSender, ArrayList<TestUserDataModel> p_userRecipient)
	{
		try
		{
			for (int i = 0; i < 5; i++)
			{
				manager.backend().searchPage().unsetUserAsHot(p_userRecipient.get(i));
				manager.backend().searchPage().unsetUserAsScammer(p_userRecipient.get(i));

				this.sendMessage(p_userSender, p_userRecipient.get(i), p_messageKey);
				if (!page().messenger().isMessagePresent(p_messageKey))
				{
					throw new TestException("Cannot send message to " + p_userRecipient.get(i).getScreenname() + " message is not found in messenger");
				}
				page().messenger().clickClose();

				manager.log().info("---------------------------------------------------");
				manager.log().info("                 message # " + (i + 1) + "               ");
				manager.log().info("---------------------------------------------------");
			}

			wd().openAutologin(testUser());
			wd().openUserProfile(p_userRecipient.get(5));
			page().messenger().clickMessenger();

			if (manager.isMD())
			{
				wd().openAutologin(p_userSender);
				wd().openUserProfile(p_userRecipient.get(5));
				// Second attempts
				page().messenger().clickMessenger();
				wd().wait(2);
				if (!page().messenger().isLargePresent())
				{
					page().messenger().clickPopOut();
				}
				page().messenger().clickMessengerInput();
				page().messenger().type("test");
			}

			// Wait for appear block payment details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentDetails, "Block 'Payment Details' doesn't appear");
			// Is payment page URL present
			wd().isUrlContains("/pay/membership?via=chat_type", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("UserPage Massager send Free 5 messages a day Upgrade redirect on payment page: " + p_ex.toString());
		}
		finally
		{
			wd().openURL(testUser().getAutologin());
			// Verifying result
			test().forErrors();
		}
	}

	/**
	 * Paid => UserPage Massager Free communication Upgrade redirect on features page
	 */
	public void freeCommunicationMessengerLinkTest(String p_messageKey, TestUserDataModel p_userSender, TestUserDataModel p_userRecipient)
	{
		try
		{
			this.sendMessage(p_userSender, p_userRecipient, p_messageKey);
			// Wait for appear link Free communication
			page().messenger().clickCommunicationBanner();
			// Wait for appear block features details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentSubscription, "Block 'Payment Subscription' doesn't appear");
			// Is features page URL present
			wd().isUrlContains("/pay/features", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("UserPage Massager Free communication Upgrade redirect on features page: " + p_ex.toString());
		}

		// Verifying result
		test().forErrors();
	}

	/**
	 * Paid => UserPage Massager Special delivery Upgrade redirect on features page
	 */
	public void specialDeliviryMessengerLinkTest(TestUserDataModel p_userRecipient)
	{
		try
		{
			wd().openAutologin(testUser());
			wd().openUserProfile(p_userRecipient);

			if (!page().messenger().isMessengerOpenned())
			{
				page().messenger().clickMessenger();
			}

			if (!page().messenger().isPopInPresent())
			{
				page().messenger().clickPopOut();
			}

			page().messenger().clickSpecialDeliveryBanner();

			// Wait for appear block features details
			wd().waitForPresence(manager.web().paymentPage().elements().blockPaymentSubscription, "Block 'Payment Subscription'");
			// Is features page URL present
			wd().isUrlContains("/pay/features", true);
		}
		catch (Exception p_ex)
		{
			log().errorAndScreen("specialDeliviryMessengerLinkTest: " + p_ex.toString());
		}

		// Verifying result
		test().forErrors();
	}

	public void sendMessage(TestUserDataModel p_userSender, TestUserDataModel p_userRecipient, String p_messageKey)
	{
		try
		{
			wd().openAutologin(p_userSender);
			wd().openUserProfile(p_userRecipient);

			if (!page().messenger().isMessengerOpenned())
			{
				page().messenger().clickMessenger();
			}

			wd().wait(2);
			if (!page().messenger().isLargePresent())
			{
				page().messenger().clickPopOut();
			}

			page().messenger().typeMessage(p_messageKey);
			page().messenger().submit();
		}
		catch (Exception p_ex)
		{
			manager.log().errorAndScreen("sendMessage " + p_ex.toString());
		}
	}

	public void sendChat(TestUserDataModel p_userSender, TestUserDataModel p_userRecipient, String p_messageKey)
	{
		try
		{
			wd().openAutologin(p_userSender);
			wd().openUserProfile(p_userRecipient);
			wd().openPage("/chat/private/id/" + p_userRecipient.getId());
			wd().wait(2); // JavaScript load
			page().inboxPage().typeMessage(p_messageKey);
			wd().wait(2); // JavaScript load
			page().inboxPage().clickSend();
			wd().wait(5); // JavaScript load
		}
		catch (Exception p_ex)
		{
			manager.log().errorAndScreen("sendChat " + p_ex.toString());
		}
	}

	public void sendLetter(TestUserDataModel p_userSender, TestUserDataModel p_userRecipient, String p_messageKey, String p_subject)
	{
		try
		{
			wd().openAutologin(p_userSender);
			wd().openUserProfile(p_userRecipient);
			wd().openPage("/inbox/letter/conversation/" + p_userRecipient.getId());
			wd().wait(2); // JavaScript load

			if (page().inboxPage().isNewLetterBtnDisplayed())
			{
				page().inboxPage().clickNewLetter();
			}

			wd().wait(2); // JavaScript load
			page().inboxPage().typeSubject(p_subject);
			wd().wait(2); // JavaScript load
			page().inboxPage().typeMessage(p_messageKey);
			wd().wait(2); // JavaScript load
			wd().scrollDown();
			wd().wait(2); // JavaScript load
			page().inboxPage().clickSendLetter();
			wd().wait(5); // JavaScript load
		}
		catch (Exception p_ex)
		{
			manager.log().errorAndScreen("sendChat " + p_ex.toString());
		}
	}

}
